<template>
  <div class="main-container" v-loading="loading" element-loading-text="努力加载中...">
    <div class="content-container">
      <div class="title-container">
        <div class="title-text">
          心律情况
        </div>
      </div>
      <div class="sleep-status-container">
        <div class="sleep-status-content">
          <div class="sleep-info-column">
            <div class="sleep-proportion-container">
              <div class="sleep-proportion-content">
                <div class="proportion-title">
                  <el-text class="proportion-text">心律占比：</el-text>
                </div>
                <div class="proportion-graph">
                  <div class="sleepInfoGraph" id="HeartRhythmStatusGraph"></div>
                </div>
                <div class="rem-info">
                  <font-awesome-icon :icon="['fas','fa-lightbulb']" size="2x" class="rem-icon"></font-awesome-icon>
                  <div class="rem-text-container">
                    <el-text class="rem-text">心律:根据AAMI标准，N类为正常心拍，暂不考虑Q类心拍</el-text>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="sleep-analysis-column">
            <div class="analysis-title">
              <el-text class="analysis-text">心律分期图：</el-text>
            </div>
            <div class="radar-graph">
              <div id="RhythmTimeGraph" class="sleepRadarGraph"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="sleep-stage-wrapper">
        <div class="sleep-stage-content">
          <view class="ahi-card2">
            <text class="ahi-text1">AAMI分类标准:<br></text>
            <text class="ahi-text2">
              AAMI EC57：2012 是由美国医疗仪器促进协会制定的一系列标准，提出心拍信号分为五类.<br>
            </text>
            <view style="margin-top: 20px;">
              <text class="ahi-text2">{{ ahiDesc.text1 }}<br></text>
              <text class="ahi-text2">{{ ahiDesc.text2 }}<br></text>
              <text class="ahi-text2">{{ ahiDesc.text3 }}<br></text>
              <text class="ahi-text2">{{ ahiDesc.text4 }}<br></text>
              <text class="ahi-text2">{{ ahiDesc.text5 }}<br></text>
            </view>
          </view>
        </div>
      </div>
      <div class="evaluation-wrapper">
        <div class="evaluation-content">
          <div class="evaluation-header">
            <div class="icon">
              <font-awesome-icon :icon="['fas','fa-file-alt']" size="2x" class="icon-color"></font-awesome-icon>
            </div>
            <div class="evaluation-title">
              <el-text class="evaluation-title-text">心律情况评估结果：</el-text>
            </div>
            <el-button v-if="enableEdit" class="edit-button" @click="showEditInput">
              <font-awesome-icon :icon="['fas','fa-pencil-alt']" class="edit-icon"></font-awesome-icon>
              <el-text class="edit-text">编辑</el-text>
            </el-button>
          </div>
          <div class="evaluation-body">
            <el-input type="textarea" class="evaluation-input" v-model="currentHeartRthythmData.evaluation" v-if="editMode"></el-input>
            <el-text v-else :span="24" class="evaluation-display">
              {{ currentHeartRthythmData.evaluation }}
            </el-text>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import '@/assets/css/reportCard.css';
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { ref, onMounted, onUnmounted, watch, markRaw } from "vue";
import * as echarts from "echarts";
import sleepData from "@/api/sleepData.js";

onMounted(() => {
  getRhythmData(props.currentReportId);
  window.addEventListener('resize', resizeCharts);
});

onUnmounted(() => {
  if (currentHeartRthythmData.value.evaluation !== evaluationBackup.value) {
    const updateSleepStateDto = {
      reportId: props.currentReportId,
      evaluation: currentHeartRthythmData.value.evaluation
    };
    sleepData.updateRhythmEvaluate(updateSleepStateDto).catch((err) => {
      console.log(err);
    });
  }
  disposeChart();
});

const props = defineProps({
  currentReportId: Number,
  enableEdit: Boolean
});

const enableEdit = ref(props.enableEdit);
const loading = ref(false);
const evaluationBackup = ref('');
const editMode = ref(false);
const currentHeartRthythmData = ref({
  proportionList: [],
  evaluation: ''
});

const ahiDesc = ref({
  text1: "N类: 正常心拍，心跳频率和节律在健康范围内;",
  text2: "S类: 室上性异常心拍，包括房性、室上性早搏等；",
  text3: "V类: 心室异常心拍，包括室性早搏、室性逸博;",
  text4: "F类: 心室融合心拍;",
  text5: "Q类: 未知心拍;"
});

const HeartRhythmChartInstance = ref(null);
const RhythmTimeChartInstance = ref(null);

const getRhythmData = (reportId) => {
  loading.value = false;
  sleepData.getRhythmData(reportId).then((res) => {
    console.log("11111111", res.data.data);
    const proportionList = res.data.data.proportionList;
    const heartRhythmTime = res.data.data.heartRhythmTime;
    currentHeartRthythmData.value = res.data.data;

    // 确保 DOM 元素存在后再初始化图表
    if (document.getElementById("HeartRhythmStatusGraph")) {
      createHeartRhythmChart(proportionList);
    }
    if (document.getElementById("RhythmTimeGraph")) {
      createRhythmTimeChart(heartRhythmTime);
    }
  });
};

const createHeartRhythmChart = (proportionList) => {
  const chartDom = document.getElementById("HeartRhythmStatusGraph");
  if (!chartDom) {
    console.error("DOM element 'HeartRhythmStatusGraph' not found!");
    return;
  }

  const filteredProportionList = proportionList.filter(item => item.value !== 0.0);
  const colors = ['#CC6699', '#66B2FF', '#666699', '#FFCC99', '#C2C2C2'];

  HeartRhythmChartInstance.value = markRaw(echarts.init(chartDom));
  HeartRhythmChartInstance.value.setOption({
    grid: {
      left: '5%',
      right: '5%',
      top: '15%',
      bottom: '0%',
      containLabel: true,
    },
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        return `${params.seriesName}<br/>心律类型: ${params.name}<br/>占比: ${(params.value * 100).toFixed(1)}%`;
      }
    },
    series: [
      {
        name: '心律占比',
        type: 'pie',
        radius: '55%',
        center: ['50%', '50%'],
        data: filteredProportionList,
        color: colors,
        label: {
          show: true,
          formatter: '{b}: {d}%',
          fontSize: 12
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }, true);
};

const createRhythmTimeChart = (heartRhythmTime) => {
  const chartDom = document.getElementById("RhythmTimeGraph");
  if (!chartDom) {
    console.error("DOM element 'RhythmTimeGraph' not found!");
    return;
  }

  const times = heartRhythmTime.times.sort((a, b) => a - b);
  const timeStrings = times.map(timestamp => {
    const date = new Date(timestamp);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  });

  const positionTimeData = heartRhythmTime.heartRhythmClass.map((state, index) => {
    return [timeStrings[index], state];
  });

  RhythmTimeChartInstance.value = markRaw(echarts.init(chartDom));
  RhythmTimeChartInstance.value.setOption({
    grid: {
      left: '10%',
      right: '5%',
      top: '5%',
      bottom: '12%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: timeStrings
    },
    yAxis: {
      type: 'category',
      data: ['N类', 'S类', 'V类', 'F类']
    },
    series: [{
      type: 'line',
      step: 'start',
      symbol: 'none',
      lineStyle: {
        color: '#0099CC'
      },
      data: positionTimeData
    }]
  }, true);
};

const resizeCharts = () => {
  if (HeartRhythmChartInstance.value) HeartRhythmChartInstance.value.resize();
  if (RhythmTimeChartInstance.value) RhythmTimeChartInstance.value.resize();
};

const disposeChart = () => {
  if (HeartRhythmChartInstance.value) HeartRhythmChartInstance.value.dispose();
  if (RhythmTimeChartInstance.value) RhythmTimeChartInstance.value.dispose();
  window.removeEventListener('resize', resizeCharts);
};

const showEditInput = () => {
  editMode.value = !editMode.value;
};

const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return hours + ':' + minutes;
};

</script>


<style scoped>
.main-container{
  width: 90%;height: 100%;background-color: #EFF2F9;border-radius: 20px
}
.content-container{
  width: 100%;height: 100%;display: flex;flex-direction: column
}
.title-container{
  width: 100%;height: 5%;margin-top: 2%
}
.title-text{
  font-size: 18px;height: 100%;margin-left: 20px;align-items: center;display: flex
}
.sleep-status-container{
  width: 100%;height: 50%;display: flex;align-items: center;justify-content: center
}
.sleep-status-content{
  height: 100%;
  width: 95%;
  display: flex;
  align-items: stretch; /* 让子元素高度一致 */
}
.sleep-info-column {
  width: 50%;
  height: 90%;
  display: flex;
  flex-direction: column;
}
.sleep-proportion-container {
  width: 90%;
  height: 100%;
  background-color: white;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.sleep-proportion-content {
  width: 90%;
  height: 90%;
  display: flex;
  flex-direction: column;
}
.proportion-title {
  width: 100%;
  height: 10%;
}
.proportion-text {
  font-size: 16px;
}
.proportion-graph {
  width: 100%;
  height: 75%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.rem-info {
  width: 100%;
  height: 15%;
  display: flex;
  align-items: center;
}
.rem-icon {
  color: #FDB800;
}
.rem-text-container {
  height: 100%;
  margin-left: 10px;
  /*overflow: hidden;*/
}
.rem-text {
  font-size: small;
  overflow: hidden;
}
@media (max-width: 1500px) {
  .rem-text {
    font-size: 12px;
  }
}
@media (max-width: 1200px) {
  .rem-text {
    font-size: 10px;
  }
}
.sleep-stage-title {
  width: 90%;
  height: 10%;
  font-size: 17px;
  margin-top: auto;
}
.sleep-analysis-column {
  width: 50%;
  height: 90%;
  background-color: white;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.analysis-title {
  width: 100%;
  height: 10%;
  /*margin-top: 10px;*/
}
.analysis-text {
  font-size: 16px;
  margin-left: 20px;
}
.radar-graph {
  width: 100%;
  height: 75%;
}
.summary-container {
  width: 100%; height: 30%; background-color: #DCEFFE; border-radius: 0 0 20px 20px; display: flex; flex-direction: column; align-items: center; justify-content: center
}
.summary-item-up {
  width: 100%; height: 40%; display: flex; align-items: center;
}
.summary-item-down{
  width: 100%; height: 50%; display: flex; align-items: center;
}
.summary-item-icon{
  width: 40px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.summary-text-container {
  flex: 1; margin-left: 5px; display: flex; flex-direction: column;
  overflow: hidden;
}
.summary-text{
  width: 100%;
  font-size: 12px;
}
@media (max-width: 1500px) {
  .summary-text {
    font-size: 11px;
  }
}
@media (max-width: 1200px) {
  .summary-text {
    font-size: 10px;
  }
}
.sleepInfoGraph{
  margin-top: 2vh;
  width: 100%;
  height: 90%;
}
.sleepRadarGraph{
  margin-top: 1vh;
  width: 100%;
  height: 100%;
}
.sleepStageGraph{
  width: 38vw ;
  height: 15vh
}
.sleep-stage-wrapper {
  width: 100%;
  height: 27%;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.sleep-stage-content {
  width: 95%;
  height: 100%;
  border-radius: 20px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}
.sleepStageGraph {
  width: 100%;
  height: 100%;
}
.evaluation-wrapper {
  width: 100%;
  height: 15%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.evaluation-content {
  width: 95%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.evaluation-header {
  width: 100%;
  height: 30%;
  display: flex;
}
.icon {
  height: 100%;
}
.icon-color {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
}
.evaluation-title {
  height: 100%;
  display: flex;
}
.evaluation-title-text {
  font-size: 17px;
  font-weight: 510;
}
.edit-button {
  height: 100%;
  margin-left: auto;
  background-color: #EFF2F9;
  border: none;
}
.edit-icon {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
  width: 20px;
  height: 20px;
}
.edit-text {
  font-size: 17px;
  color: #3DD986;
}
.evaluation-body {
  width: 100%;
  height: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.evaluation-input {
  height: 100%;
  width: 95%;
}
.evaluation-display {
  width: 90%;
  font-size: 15px;
  margin-left: 30px;
  margin-top: 10px;
}

/*.ahi-card2 {*/
/*  flex: 1;*/
/*  margin: 20px;*/
/*  padding: 20px;*/
/*  background-color: #F9F7F3;*/
/*  border-radius: 16px;*/
/*  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);*/
/*  margin-top: 20px;*/
/*}*/
.ahi-text1 {
  font-size: 20px;
  color: #34495E;
  /* 深蓝色 */
  font-weight: bold;
  margin-bottom: 5px;
}

.ahi-text2 {
  /*margin-left: 5px;*/
  font-size: 17px;
  color: #7C8B99;
  line-height: 28px;
}

.ahi-text2 .bar-container {
  position: relative;
  margin-top: 20px;
}

.ahi-text2 .bar-card {
  display: flex;
  width: 100%;
  height: 50px;
  border-radius: 25px;
  overflow: hidden;
  background-color: #F0F4FF;
}

.ahi-text2 .bar-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28px;
  font-weight: bold;
}

.ahi-text2 .normal {
  background-color: #A8D5BA;
}

.ahi-text2 .mild {
  background-color: #FFD59A;
}

.ahi-text2 .moderate {
  background-color: #FFAB76;
}

.ahi-text2 .severe {
  background-color: #FF6F61;
}

.ahi-text2 .index-move {
  position: absolute;
  bottom: -25px;
  width: 50px;
  height: 50px;
  transition: margin-left 0.3s ease;
}
</style>